#!/usr/bin/python
# -*- coding: UTF-8 -*-

from lib.base import Douyin
from sms.sms import Sms
from random import randint
import random, logging, sys, re
from faker import Faker
from threading import Thread

from exception.error import ImageYanzhengmaRuntimeError
from exception.error import PhoneCodeTimeoutRuntimeError
from exception.error import PhoneCodeWrongRuntimeError
from exception.error import PhoneBannedRuntimeError

class Upload(Douyin):
    def __init__(self, sn):
        super(Upload, self).__init__(sn)
        fd = open("log/uploadmedia/{}.log".format(sn), "w")
        sys.stdout = sys.stderr = fd

    def broadcast(self, name):
        self.device.shell("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:///sdcard/DCIM/Camera/{}.mp4".format(name), timeout=10)

    # 检测今日头条
    def threadCheckSuccess1(self):
        logging.warning("检测今日头条线程执行")
        while True:
            self.device(resourceId="com.ss.android.ugc.aweme:id/akz").click_exists()

    # 检测验证码
    def threadCheckSuccess2(self):
        logging.warning("检测验证码线程执行")
        while True:
            self.device(resourceId="com.ss.android.ugc.aweme:id/akz").click_exists()

    def pushVedio(self, path):
        names = [self.sn, "Z"]
        logging.warning("delete")
        for name in names:
            self.device.shell("rm sdcard/DCIM/Camera/{}.mp4".format(name))
            self.broadcast(name)

        logging.warning("upload")
        self.device.push(path, "sdcard/DCIM/Camera/{}.mp4".format(self.sn))
        self.broadcast(self.sn)

        self.sleep(2)

        self.device.shell("cp sdcard/DCIM/Camera/{}.mp4 sdcard/DCIM/Camera/Z.mp4".format(self.sn))
        self.broadcast("Z")

    def upload(self, title):

        self.raiseErrorWapper(self.device(resourceId="com.ss.android.ugc.aweme:id/byo").click_exists(timeout=60), "60s未找到上传按钮")
        self.check_voice_permission()

        logging.warning("选择第一个视频")
        self.click_first_video()

        logging.warning("点下一步")
        self.device(resourceId="com.ss.android.ugc.aweme:id/mw").click_exists(timeout=30)

        self.sleep(2)

        logging.warning("点下一步")
        self.device(resourceId="com.ss.android.ugc.aweme:id/rx").click_exists(timeout=30)

        logging.warning("输入标题")
        #self.device(className="android.widget.EditText").click()
        #self.write_text(title)
        self.device(resourceId="com.ss.android.ugc.aweme:id/as1").set_text(title)

        logging.warning("发布")
        self.device(resourceId="com.ss.android.ugc.aweme:id/ase").click()

        uploadingTextExists = False
        # 我知道了
        self.device(resourceId="com.ss.android.ugc.aweme:id/an2").click_exists(timeout=5)
        if self.device(textContains="上传中").exists(timeout=3):
            uploadingTextExists = True
        self.device(resourceId="com.ss.android.ugc.aweme:id/an2").click_exists(timeout=5)

        while self.device(textContains="上传中").exists(timeout=10):
            uploadingTextExists = True
            logging.warning("上传中")
            self.sleep(5)

        if not uploadingTextExists:
            self.sleep(300)

        # 今日头条
        self.device(resourceId="com.ss.android.ugc.aweme:id/aci").click_exists(timeout=10)
        # 我知道了
        #self.device(resourceId="com.ss.android.ugc.aweme:id/an2").click_exists(timeout=30)

        if self.device(text="上传失败，已保存至草稿箱").exists:
            return False

        if self.check_is_image_verify():
            raise("弹验证码了")

        return True

    def start_by_pname(self, pname, path, title):
        logging.warning("start")
        self.device.healthcheck()
        #Thread(target=self.threadCheckSuccess1).start()
        #Thread(target=self.threadCheckSuccess2).start()
        if self.open_douyin_by_packname(pname):
            if self.check_is_not_login():
                raise RuntimeError("没有登录")
                
            self.pushVedio(path)
            for i in range(3):
                self.upload(title)

        raise RuntimeError("没有打开douyin")

    def start(self, path, title, app_id):
        logging.warning("start")
        self.device.healthcheck()
        if self.open_douyin(app_id):
            for i in range(3):
                self.check_window()
                
            self.pushVedio(path)
            for i in range(3):
                self.upload(title)
        return False

        

    


